<template>
    <el-upload
        accept=".png,.jpeg,.jpg,.webp"
        action="/api/sys/file/upload"
        withCredentials
        v-model:fileList="images"
        :show-file-list="false"
        :before-upload="beforeAvatarUpload"
        :disabled="disabled"
        :on-success="uploadSuccess"
        :on-remove="remove"
        :multiple="false"
    >
        <div class="content">
            <el-avatar class="icon" v-if="images.length < 1" icon="User" size="large"> </el-avatar>
            <el-avatar :src="model" v-else size="large"></el-avatar>
            <!-- <div class="edit">编辑</div> -->
        </div>

        <template #tip v-if="tip">
            <div class="remark">{{ tip }}</div>
        </template>
    </el-upload>
</template>
<script setup>
import { onMounted } from "vue";

const props = defineProps({
    disabled: Boolean,
    tip: { type: String },
});
const model = defineModel({});
const images = ref([]);

onMounted(() => {
    if (model.value) {
        images.value.push({
            url: model.value,
        });
    }
});

function beforeAvatarUpload(rawFile) {
    if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error("图片大小不能超出10M");
        return false;
    }
    return true;
}

function remove({ url }) {
    model.value = null;
    return;
}

function uploadSuccess(res) {
    model.value = res.url;
}
</script>

<style lang="scss" scoped>
.content {
    position: relative;

    .edit {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        text-align: center;
        color: var(--primary_color);
        background: #3e62d822;
        line-height: 1;
        padding: 2px 0;
    }
}
</style>
